const cloud = require("@cloudbase/node-sdk");

const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV,
});

var db = app.database();
const _ = db.command
const $ = db.command.aggregate
const ZXBooth = db.collection('ZX-Booth')
const ZXData = db.collection('ZX-Data')
const ZXUser = db.collection('ZX-User')
const nowDate = db.serverDate()
const nowDate2 = new Date().getTime()

// 获取openId云函数入口函数
exports.main = async (event,context,token,gameId) => {
    process.env.TZ = 'Asia/Shanghai'

    var params = {}
    var api = event.api
    var _id = event.data._id
    var goodsName = event.data.goodsName
    var onSale = event.data.onSale
    var classStr = event.data.classStr
    var goodsId = event.data.goodsId
    
    params.gameId = gameId

    if(token){
        // 编辑和新增个人摊位物品
        if(api=='api-booth-edit'){
            if (_id){
                // 编辑个人摊位
                delete event.data._id
                return await ZXBooth.doc(_id).update(event.data)
            }else{
                // 默认添加上架状态
                event.data.onSale = true
                event.data.userId = token
                event.data.gameId = gameId
                event.data.create_time = nowDate2;

                if(goodsId)
                    params.goodsId = goodsId
                    params.userId = token
                
                // 判断是否已经添加此物品
                const total =  (await ZXBooth.where(params).count()).total
                if(total){
                    return {
                        type: 'error',
                        msg: '此物品已经添加！'
                    }
                }else{
                    return await ZXBooth.add(event.data)
                }
            }
        }
        // 删除个人摊位物品
        if(api=='api-booth-del'){
            if (_id){
                return await ZXBooth.doc(_id).remove()
            }
        }

        // 获取个人摊位
        if(api=='api-booth-list-my'){
            if (goodsName)
                params.goodsName = goodsName
            if (onSale!=null)
                params.onSale = Boolean(onSale)
            if(classStr)
                params.class = String(classStr)
            params.userId = token
            const res = await db
            .collection('ZX-Booth')
            .aggregate()
            .lookup({
                from: 'ZX-Data',
                localField: 'goodsId',
                foreignField: '_id',
                as: 'goodsList'
            })
            .replaceRoot({
                newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
            })
            .project({
                goodsList: 0
            })
            .match(params)
            .sort({
                "class": 1,
            })
            .skip((event.data.pageIndex - 1) * event.data.pageSize)
            .limit(event.data.pageSize)
            .end()

            const list = res.data
            const total = (await ZXBooth.where(params).count()).total

            return {
                list: list,
                total: total,
            }
        }
    }

    // 获取所有摊位
    if (api=='api-booth-list-all'){

        var goodsParams = {}
        var sortParams = {}
        var name = event.data.name
        var sex = event.data.sex
        var levelMin = event.data.levelMin
        var levelMax = event.data.levelMax
        var pinzhi = event.data.pinzhi
        var priceType = event.data.priceType
        var sort = event.data.sort?event.data.sort:1

        var className = event.data.class
        var goodsType = event.data.goodsType

        if (name)
            params.goodsName = db.RegExp({
                regexp: String(name),
                options: 'i',
            })
        if (priceType)
            params.priceType = priceType
        if (sort)
            sortParams.money = sort
        if (className)
            params.class = className
        if (sex)
            params.sex = sex
        if (pinzhi)
            params.pinzhi = pinzhi
        if (levelMin || levelMax)
            params.level = _.gte(levelMin).and(_.lte(levelMax))
        if (goodsType)
            params.type = goodsType
        
        // 默认只获取上架的物品
        params.onSale = true
        params.number = _.gt(0)

        sortParams.create_time = -1

        const res = await db
            .collection('ZX-Booth')
            .aggregate()
            .lookup({
                from: 'ZX-Data',
                localField: 'goodsId',
                foreignField: '_id',
                as: 'goodsList'
            })
            .replaceRoot({
                newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
            })
            .lookup({
                from: 'ZX-User',
                localField: 'userId',
                foreignField: '_id',
                as: 'userList'
            })
            .replaceRoot({
                newRoot: $.mergeObjects([$.arrayElemAt(['$userList', 0]), '$$ROOT'])
            })
            .project({
                goodsList: 0,
                userList: 0,
                password: 0,
                powerInfo: 0,
            })
            .match(params)
            .sort(sortParams)
            .skip((event.data.pageIndex - 1) * event.data.pageSize)
            .limit(event.data.pageSize)
            .end()
        const list = res.data

        const total = await db
        .collection('ZX-Booth')
        .aggregate()
        .match(params)
        .lookup({
            from: 'ZX-Data',
            localField: 'goodsId',
            foreignField: '_id',
            as: 'goodsList'
        })
        .lookup({
            from: 'ZX-User',
            localField: 'userId',
            foreignField: '_id',
            as: 'userList'
        })
        .match(goodsParams)
        .count('total')
        .end()

        // total.data[0].tatal,
        var tatalCount = 0
        if(total.data&&total.data.length>0){
            tatalCount = total.data[0].total
        }
        return {
            list: list,
            total: tatalCount
        }
    }
};